package com.qf.xiaomi.service.impl;

import com.qf.xiaomi.dao.AddressDao;
import com.qf.xiaomi.dao.impl.AddressDaoImpl;
import com.qf.xiaomi.pojo.TbAddress;
import com.qf.xiaomi.service.AddressService;

import java.util.List;

/**
 * @Created by 马英超 on 2022/8/20 10:52
 * @author： 马英超
 * @version：v1.0
 * @description:
 */
public class AddressServiceImpl implements AddressService {
    /**
     * 增加地址
     * @param id
     * @param name
     * @param phone
     * @param detail
     * @return
     */
    @Override
    public int addAddress(int id, String name, String phone, String detail) {
      /*  调用dao层*/
        AddressDao addressDao=new AddressDaoImpl();
     final int  addResult=   addressDao.addAddressInfo(id,name,phone,detail);
        if(addResult>0){
            return addResult;
        }
        return 0;//新增失败
    }

    /**
     * 删除地址
     * @param id
     * @param userId
     * @return
     */
    @Override
    public int deleteAddress(int id, int userId) {
        AddressDao addressDao=new AddressDaoImpl();
        final int  deleteResult=   addressDao.deleteAddressInfo(id,userId);
        if(deleteResult>0){
            return deleteResult;
        }
        return 0;
    }

    /**
     * 设置默认地址
     * @param id
     * @param userId
     * @return
     */
    @Override
    public int setDefaultAddress(int id, int userId) {
        AddressDao addressDao=new AddressDaoImpl();
        //根据传入的参数查询是否已经设置了默认值，如果设置了则将原来的默认值更新，然后再更新需要设置默认值的地址
        final int queryDefaultAddressInfo = addressDao.queryDefaultAddressInfo(userId);
        if(queryDefaultAddressInfo>0){
            //调用Dao中的方法将原来的默认地址设置为普通地址，并在此调用Dao中的方法将目标地址设置为默认地址
            final int udateDefaultAddressInfo = addressDao.udateDefaultAddressInfo(userId);
            if (udateDefaultAddressInfo>0){
                final int  setDefaultResult = addressDao.setDefaultAddressInfo(id, userId);
                if (setDefaultResult>0)
                    return setDefaultResult;
                return 0;
            }else{
                return 0;
            }
        }else{
            final int setResult=   addressDao.setDefaultAddressInfo(id,userId);
            if(setResult>0){
                return setResult;
            }
            return 0;
        }


    }

    /**
     * 修改地址
     * @param id
     * @param name
     * @param phone
     * @param detail
     * @param userId
     * @return
     */
    @Override
    public int updateAddress(int id,String name,String phone, String detail,int userId) {
        AddressDao addressDao=new AddressDaoImpl();
        final int  updateResult=   addressDao.updateAddressInfo(id,name,phone,detail,userId);
        if(updateResult>0){
            return updateResult;
        }
        return 0;
    }

    @Override
    public List<TbAddress> queryAddressByUserId(int userId){
        //调用dao
        AddressDao addressDao=new AddressDaoImpl();
     return addressDao.queryAddressInfoByUserId(userId);

    }

}
